import request from '../utils/request';
import { ElMessage, arrayBufferToString } from '/src/utils'

import { getStorageValue, setStorageValue } from '/src/utils'

export const post = (module, method, query, config) => {
    let isDev
    try {
        // console.log('env', import.meta.env)
        if (import.meta.env.MODE == "development") {
            isDev = true
        }
    }catch(ex) {
        console.error('ex', ex)
    }
    config = {...(config||{})}
    let sortInfo = config.sortInfo
    delete config.sortInfo
    let urlPrefix = getStorageValue('url_prefix')
    if (window.url_prefix) {
        urlPrefix = window.url_prefix
    }
    let url
    if (urlPrefix) {
        url = urlPrefix + module+'/'+method
    } else {
        if (isDev) {
            url = '/api2/' + module+'/'+method
        } else {
            url = module+'/'+method
        }
    }
    return request({
        url,
        method: 'post',
        data: query,
        ...(config||{}),
    })
    .then( (response) => {
        let {data, config} = response
        if (!data) {
            if (config.withConfig) {
                return response
            }
            return data;
        }
        if ((config||{}).responseType === 'arraybuffer') {
            let hasError = false
            try {
                if (data.byteLength > 10 && data.byteLength < 500) {
                    let err = JSON.parse(arrayBufferToString(data))
                    console.error('err', err)
                    if (err.code && err.msg) {
                        hasError = true
                        data = err
                    }
                }
            }catch(ex) {
                if (ex.message && ex.message.indexOf('in JSON at') >= 0) {

                } else {
                    console.error('ex', ex)
                }
            }
            if (!hasError) {
                if (config.withConfig) {
                    return response
                }
                return data;
            }
        }
        if (data.code) {
            ElMessage.error(data.msg);
            return Promise.reject(new Error(data.msg));
        }

        if (config.withConfig) {
            return response
        }

        if (data.body && data.body instanceof Array) {
            if (sortInfo && sortInfo instanceof Array) {
                return data.body.sort(function compareFunction(param1, param2) {
                    for(let i in sortInfo) {
                        let direction = 1;
                        let p = sortInfo[i]
                        if (typeof(p) !== 'string') {
                            for(let pi in p) {
                                direction = p[pi] == 'asc' ? 1 : -1;
                                p = pi
                            }
                        }
                        let v1 = param1[p]
                        let v2 = param2[p]
                        let ret = 0;
                        if (typeof(v1) === 'number' && typeof(v2) === 'number') {
                            ret = v1 - v2;
                        }
                        if (ret) {
                            return ret * direction;
                        }
                        if (typeof(v1) === 'string' && typeof(v2) === 'string') {
                            ret = v1.localeCompare(v2, 'zh')
                        }
                        if (ret) {
                            return ret * direction;
                        }
                        ret = (v1+'').localeCompare((v2+''), 'zh')
                        if (ret) {
                            return ret * direction;
                        }
                    }
                    return 0;
                })
            }
            return data.body
        }

        if ('body' in data && data.body !== null) {
            return data.body
        }
        return data
    })
    .catch( error => {
        console.error('config', config)
        console.error('error2', url, config, query, error, 'error', error+'')
        console.error('url', url)
        console.error('query', query)
        console.error('error', error)
        console.error('error.msg', error.msg)
        if ((error+'').indexOf('Request failed with status code 502') >= 0) {
            error = new Error('服务端正在重启，请稍后重试');
        }
        return Promise.reject(error);
    })
}